﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Grimgine.Core
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class Singleton<T> where T : class
    {
        /// <summary>
        /// 
        /// </summary>
        private static T instance;

        /// <summary>
        /// 
        /// </summary>
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    CreateInstance();
                }

                return instance;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private static void CreateInstance()
        {
            if (instance == null)
            {
                Type t = typeof(T);

                ConstructorInfo[] ctors = t.GetConstructors();
                if (ctors.Length > 0)
                {
                    throw new InvalidOperationException(String.Format("{0} has at least one accessible ctor making it impossible to enforce singleton behaviour", t.Name));
                }

                instance = (T)Activator.CreateInstance(t, true);
            }
        }
    }
}
